
#requires -version 3

<#
.SYNOPSIS 
Download MDTEx Components

.DESCRIPTION
Download a collection of MDT components listed in a Config File from the internet 

.NOTES
Copyright Keith Garner (KeithGa@DeploymentLive.com), All rights reserved.

.LINK
http://MDTEx.CodePlex.com

#>

[CmdletBinding()]
param(
    [switch] $Everything,
    [switch] $SkipPostProcess,
    [switch] $BitsTransfer,
    [string] $DownloadPath
)

if ( -not $DownloadPath ) { $DownloadPath = $PSScriptRoot }

Write-Verbose "Import .\Downloads.csv"
$DownloadList = Import-Csv -Path $PSScriptRoot\Downloads.csv
if (-not $Everything) 
{
    $DownloadList = $DownloadList | out-gridview -OutputMode Multiple -Title "Files to Download"
}

Write-Verbose "Construct Desination Folders"
New-Item -ItemType Directory -Force -Path $DownloadList.Destination -ErrorAction SilentlyContinue | Out-Null

Write-Verbose "Downloads Files"
$DownloadListReady = $DownloadList | Where-Object { -not ( Test-Path "$DownloadPath\$($_.Destination)\*" ) } | Where-Object { $_.Source }
if ( $BitsTransfer )
{
    $DownloadListReady | Start-BitsTransfer | Out-String |Write-Verbose
}
else
{
    $DownloadListReady | %{ Invoke-WebRequest -Uri $_.Source -OutFile (Join-Path "$DownloadPath\$($_.Destination)" (Split-Path -Leaf $_.Source) ) -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::FireFox } | Out-String |Write-Verbose
}

if ( -not $SkipPostProcess )
{
    Write-Verbose "Post Processing"
    $DownloadList | Where-Object { $_.PostProcess } | ForEach-Object {
        write-Verbose "Run Custom Command: $($_.ID) at $($_.Destination) $($_.PostProcess)"
        Push-Location -Path "$DownloadPath\$($_.Destination)"
        invoke-expression  $_.PostProcess
        Pop-Location
    }
}

Write-Verbose "Done"
